Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

MkDiagram

github Show source on GitHub

Class representing a mermaid diagram.

Note

Description

MkDiagrams can show directed acyclic graphs and allows to manually create diagrams.

Examples

Example: Regular

Note

Jinja

{{ ["1", "2", "3"] | MkDiagram(connections=[("1", "2"), ("2", "3")]) }}

Note

Python

MkDiagram(['1', '2', '3'], {('1', '2'), ('2', '3')})
Rendered
graph TD
  1
  2
  3
  1 --> 2
  2 --> 3
Markdown
````mermaid
graph TD
  1
  2
  3
  1 --> 2
  2 --> 3
````
Html
<pre><code class="language-mermaid">graph TD
  1
  2
  3
  1 --&gt; 2
  2 --&gt; 3
</code></pre>

GitHub
````mermaid
graph TD
  1
  2
  3
  1 --> 2
  2 --> 3
````

Example: Direction

Note

Jinja

{{ ["1", "2", "3"] | MkDiagram(connections=[("1", "2"), ("2", "3", "comment")], direction="LR") }}

Note

Python

MkDiagram(['1', '2', '3'], {('1', '2'), ('2', '3', 'comment')}, direction='LR')
Rendered
graph LR
  1
  2
  3
  1 --> 2
  2 --> |comment| 3
Markdown
````mermaid
graph LR
  1
  2
  3
  1 --> 2
  2 --> |comment| 3
````
Html
<pre><code class="language-mermaid">graph LR
  1
  2
  3
  1 --&gt; 2
  2 --&gt; |comment| 3
</code></pre>

GitHub
````mermaid
graph LR
  1
  2
  3
  1 --> 2
  2 --> |comment| 3
````
DocStrings

class MkDiagram(mkcode.MkCode)
Sub classes
NameChildrenInherits
MkClassDiagram
mknodes.templatenodes.mkclassdiagram
Node to display the class hierarchy of a class. Supports multiple modes.
    MkPipDepTree
    mknodes.templatenodes.mkpipdeptree
    Node to display a mermaid diagram for the dependencies.
      Base classes
      NameChildrenInherits
      MkCode
      mknodes.basenodes.mkcode
      Class representing a Code block.
      ⋔ Inheritance diagram
      graph TD
        1128373226["mkdiagram.MkDiagram"]
        1761293797["mkcode.MkCode"]
        835538629["mkcontainer.MkContainer"]
        1956333208["mkcontainer.MkContainerBase"]
        1359323199["mknode.MkNode"]
        2751680898["builtins.object"]
        1761293797 --> 1128373226
        835538629 --> 1761293797
        1956333208 --> 835538629
        1359323199 --> 1956333208
        2751680898 --> 1359323199
      
      NodeFile

      /home/runner/work/mknodes/mknodes/src/mknodes/basenodes/mkdiagram/metadata.toml

      [metadata]
      icon = "mdi:graph-outline"
      name = "MkDiagram"
      group = "diagram"
      
      [[requirements.extension."pymdownx.superfences".custom_fences]]
      name = "mermaid"
      class = "mermaid"
      format = "pymdownx.superfences.fence_code_format"
      
      [examples.regular]
      title = "Regular"
      jinja = """
      {{ ["1", "2", "3"] | MkDiagram(connections=[("1", "2"), ("2", "3")]) }}
      """
      
      [examples.direction]
      title = "Direction"
      jinja = """
      {{ ["1", "2", "3"] | MkDiagram(connections=[("1", "2"), ("2", "3", "comment")], direction="LR") }}
      """
      
      [output.markdown]
      template = """
      {{ node.fence_boundary }} mermaid
      graph {{ node.direction }}
      {% if node.connections %}
      {% for name in node.names %}
        {{ name }}
      {% endfor %}
      {% for connection in node.connections %}
      {% if connection | length == 2 %}
        {{ connection[0] }} --> {{ connection[1] }}
      {% else %}
        {{ connection[0] }} --> |{{ connection[2] }}| {{ connection[1] }}
      {% endif %}
      {% endfor %}
      {% else %}
      {% for name in node.names %}
        {{ name | get_hash }}["{{ name }}"]
      {% endfor %}
      {% for prev, nxt in node.names | pairwise %}
        {{ prev | get_hash }} --> {{ nxt | get_hash }}
      {% endfor %}
      {% endif %}
      {{ node.fence_boundary }}
      """
      
      
      Code

      mknodes.basenodes.mkdiagram.MkDiagram

      class MkDiagram(mkcode.MkCode):
          """Class representing a mermaid diagram.
      
          MkDiagrams can show directed acyclic graphs and allows to manually
          create diagrams.
          """
      
          ICON = "material/graph-outline"
          REQUIRED_EXTENSIONS = [resources.Extension("pymdownx.superfences", **config)]
      
          def __init__(
              self,
              names: list[str] | None = None,
              connections: list[tuple[str, str] | tuple[str, str, str]] | None = None,
              *,
              direction: Literal["TD", "DT", "LR", "RL"] = "TD",
              **kwargs: Any,
          ) -> None:
              """Constructor.
      
              Args:
                  names: names which should be part of the diagram
                  connections: tuples indicating the connections of the names
                  direction: diagram direction
                  kwargs: Keyword arguments passed to parent
              """
              super().__init__(language="mermaid", **kwargs)
              self.direction = direction
              # Preserve order. Useful if only names are passed, order is important then.
              self.names = iterfilters.reduce_list(names or [])
              self.connections = set(connections or [])
      
          def get_text(self) -> str:
              """MkCode override."""
              return f"graph {self.direction}\n{self.get_mermaid_code()}"
      
          def get_mermaid_code(self) -> str:
              """Return code block, excluding fences and (graph type direction) line.
      
              Can be overriden by subclasses.
              """
              lines = list(self.names)
              if not self.connections:
                  lines = [f'{utils.get_hash(i)}["{i}"]' for i in lines]
                  for prev, nxt in itertools.pairwise(self.names):
                      lines.append(f"{utils.get_hash(prev)} --> {utils.get_hash(nxt)}")
                  return textwrap.indent("\n".join(lines), "  ")
              for connection in self.connections:
                  if len(connection) == 2:  # noqa: PLR2004
                      source, target = connection
                      lines.append(f"{source} --> {target}")
                  elif len(connection) == 3:  # noqa: PLR2004
                      source, target, mark = connection
                      lines.append(f"{source} --> |{mark}| {target}")
                  else:
                      msg = f"Tuple with wrong length: {connection}"
                      raise TypeError(msg)
              return textwrap.indent("\n".join(lines), "  ")
      
          @property
          def fence_title(self) -> str:
              """MkCode override."""
              return "mermaid"
      
      
      Page info
      Code for this page

      mknodes.manual.nodes_section.create_section_for_nodes

      def create_section_for_nodes(
          nav: mk.MkNav,
          klasses: Sequence[type[mk.MkNode]],
      ) -> mk.MkTable:
          table = mk.MkTable(columns=["Node", "Docstrings", "Markdown extensions"])
          for kls in klasses:
              tpl = "classpage_custom.jinja"
              page = mk.MkClassPage(kls, icon=kls.ICON, template_path=tpl, parent=nav, hide="toc")
              nav += page
              if kls.STATUS:
                  page.metadata.status = kls.STATUS
              elif kls.JS_FILES:
                  page.metadata.status = "js"
              elif kls.CSS:
                  page.metadata.status = "css"
              page.created_by = create_section_for_nodes
              link = mk.MkLink(page, kls.__name__, icon=kls.ICON)
              extensions = ", ".join(f"`{i}`" for i in kls.REQUIRED_EXTENSIONS)
              table.add_row((link, kls.__doc__, extensions))
          return table
      
      
      Resources
      Resources(css=[],
                markdown_extensions={'admonition': {},
                                     'pymdownx.details': {},
                                     'pymdownx.highlight': {'anchor_linenums': True,
                                                            'line_spans': '__span',
                                                            'pygments_lang_class': True},
                                     'pymdownx.superfences': {'custom_fences': [{'class': 'mermaid',
                                                                                 'format': <function fence_code_format at 0x7d707a397060>,
                                                                                 'name': 'mermaid'}]},
                                     'pymdownx.tabbed': {},
                                     'tables': {}},
                plugins=[Plugin('mkdocstrings')],
                js=[],
                assets=[],
                packages=[])
      
      Metadata
      created:
        source_filename: /home/runner/work/mknodes/mknodes/src/mknodes/manual/nodes_section.py
        source_function: create_section_for_nodes
        source_line_no: 93
      hide:
      - toc
      icon: material/graph-outline
      title: MkDiagram